package com.xiongwei.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Java标准库的java.io.File表示一个文件或者目录
 *
 * 创建File对象本身不涉及IO操作
 * 可以获取路径/绝对路径/规范路径
 * 可以获取目录的文件和子目录
 * 可以创建或删除文件和目录
 *
 * @author XiongWei
 * @date 2021/1/7
 */
public class FileObject {

    public static void main(String[] args) throws IOException {
        FileObject fo = new FileObject();
//        fo.testDeleteFile();
//
//        fo.testCreateFile();

//        fo.test();

        fo.readFile2();
    }

    public void testGetPath() throws IOException {
        /**
         * getPath():返回构造方法传入的路径
         * getAbsolutePath():返回绝对路径
         * getCanonicalPath():类似绝对路径,返回的是规范路径
         */
        //绝对路径可以表示成C:\Windows\System32\..\notepad.exe，而规范路径就是把.和..转换成标准的绝对路径后的路径：C:\Windows\notepad.exe。
        File file3 = new File("../pojo/User.java");
        System.out.println(file3.getPath());
        System.out.println(file3.getAbsolutePath());
        System.out.println(file3.getCanonicalPath());

        System.out.println("=================================");
    }

    public void testDeleteFile() {
        File file = new File("/Users/apple/Documents/office/test.txt");
        boolean delete = file.delete();
        System.out.println(delete);
    }

    public void testCreateFile() throws IOException {
        File file = new File("/Users/apple/Documents/office/xiongwei.txt");
        if (file.createNewFile()) {
            System.out.println(file.getName());
        }
    }

    public void test() {
        //有"/"获取当前类所在工程的路径,无"/"获取当前类的绝对路径
        File file = new File(this.getClass().getResource("").getPath());
        File file2 = new File(this.getClass().getResource("/").getPath());
        //默认路径为项目路径
        File file3 = new File("src/com/xiongwei");
        System.out.println(file);
        System.out.println(file2);
        System.out.println(file.getName());
        System.out.println(file.isFile());
        System.out.println(file.isDirectory());
        System.out.println(file.getAbsolutePath());

        System.out.println(file3);
        System.out.println(file3.isDirectory());
        System.out.println(file3.getAbsolutePath());
    }

    public void readFile() throws IOException {
        InputStream is = null;
        try {
            is = new FileInputStream("src/com/xiongwei/io/io简介.txt");
            int n;
            while ((n = is.read()) != -1) {
                System.out.println(new char[n]);
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public void readFile2() throws IOException {
        Reader is = null;
        try {
            is = new FileReader("src/com/xiongwei/io/io简介.txt", StandardCharsets.UTF_8);
            int n;
            while ((n = is.read()) != -1) {
                System.out.print((char)n);
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}
